<script setup>
import { computed, inject, onMounted, ref, watch } from 'vue';
import { ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons-vue';

import * as utils from 'video-action/libs/utils.js';
import VideoPlayer from 'video-action/annotation/components/VideoPlayer.vue';

const mainState = inject('mainState');
const video = inject('video');
const layers = inject('layers');
const classes = inject('classes');
const annotationState = inject('annotationState');

// common
const CANVAS_WIDTH = 1920;
const canvasHeight = computed(() => video.value ? (CANVAS_WIDTH * video.value.height) / video.value.width : 0);
const props = defineProps({
  position: {
    type: String,
    required: true,
  },
});
const currentFrame = computed(() => annotationState.value.frame[props.position]);

// background
/** @type {import('vue').Ref<HTMLCanvasElement>} */
const background = ref()
onMounted(() => {
  const ctxBMR = background.value.getContext('bitmaprenderer')
  watch(
    () => annotationState.value.cachedFrameList[annotationState.value.frame[props.position]],
    (frame) => {
      if (frame)
        createImageBitmap(frame).then((image) => {
          ctxBMR.transferFromImageBitmap(image)
        })
    },
    {
      immediate: true
    }
  )
})

const actionList = computed(() =>
  layers.value
  .filter(layer => utils.time2index(video.value.fps, layer.start) <= currentFrame.value && currentFrame.value <= utils.time2index(video.value.fps, layer.end))
  .map((layer) => classes.value.find((label => label === layer.action)))
)


const handleZoomClick = () => {
  mainState.value.zoom = !mainState.value.zoom;
}
</script>

<template>
  <div>
    <div class="filmstrip"></div>
    <main>
      <canvas
        ref="background"
        style="filter: none;"
        :width="CANVAS_WIDTH"
        :height="canvasHeight"
      >
      </canvas>
      <VideoPlayer v-if="position === 'left'" />
      <a-button
        v-if="position === 'left'"
        style="position: absolute; top: 5px; right: 5px"
        shape="circle"
        @click="handleZoomClick"
      >
        <template #icon>
          <template v-if="mainState.zoom">
            <zoom-out-outlined />
          </template>
          <template v-else>
            <zoom-in-outlined />
          </template>
        </template>
      </a-button>
      <div
        v-if="actionList && actionList.length"
        class="actions"
      >
        {{ actionList.join(',') }}
      </div>
    </main>
    <div class="filmstrip"></div>
  </div>
</template>

<style>
.actions {
  position: absolute;
  left: 0;
  bottom: 0;
  font-size: 2em;
  color: #fff;
  text-shadow: 0 -1px 1px #000;
  background-color: rgba(0,0,0,.3);
}

.filmstrip {
  width: 100%;
  height: 20px;
  background-image: url(/filmstrip.png);
  background-repeat: repeat-x;
}
</style>
